﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using hao_Common.Response.Extensions;

namespace hao_Product.Api.Controllers
{
    /// <summary>
    /// 文件上传控制器
    /// </summary>
    [ApiController]
    [Route("api/upload")]
    public class UploadController : ControllerBase
    {
       private readonly IWebHostEnvironment _env;
       private readonly ILogger<UploadController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="env">环境变量</param>
        /// <param name="logger">日志记录器</param>
        public UploadController(IWebHostEnvironment env, ILogger<UploadController> logger)
        {
            _env = env;
            _logger = logger;
        }

        /// <summary>
        /// 上传图片文件
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <returns>上传结果</returns>
        /// <response code="200">上传成功</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="413">文件过大</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("upload_img")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(413)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> UploadImage([FromForm] IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                    return this.ValidationFailResult("未选择文件");

                // 文件大小校验 (5MB)
                const long maxFileSize = 5 * 1024 * 1024;
                if (file.Length > maxFileSize)
                    return this.ValidationFailResult("文件大小不能超过5MB");

                // 文件类型校验
                var allowedTypes = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var ext = Path.GetExtension(file.FileName).ToLower();
                if (!allowedTypes.Contains(ext))
                    return this.ValidationFailResult("只允许上传图片文件（jpg、jpeg、png、gif、bmp、webp）");

                // 路径处理
                var uploadsDir = Path.Combine(_env.WebRootPath, "uploads");
                if (!Directory.Exists(uploadsDir))
                    Directory.CreateDirectory(uploadsDir);

                // 生成唯一文件名
                var fileName = Guid.NewGuid() + ext;
                var filePath = Path.Combine(uploadsDir, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回相对路径URL
                var url = $"/uploads/{fileName}";
                
                _logger.LogInformation("文件上传成功: {FileName} -> {Url}", file.FileName, url);
                
                return this.SuccessResult(new { url }, "文件上传成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件上传失败: {FileName}", file?.FileName);
                return this.ServerErrorResult("文件上传失败");
            }
        }

        /// <summary>
        /// 批量上传图片文件
        /// </summary>
        /// <param name="files">图片文件列表</param>
        /// <returns>上传结果</returns>
        /// <response code="200">上传成功</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="413">文件过大</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("upload_imgs")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(413)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> UploadImages([FromForm] List<IFormFile> files)
        {
            try
            {
                if (files == null || files.Count == 0)
                    return this.ValidationFailResult("未选择文件");

                if (files.Count > 6)
                    return this.ValidationFailResult("最多只能上传6个文件");

                var urls = new List<string>();
                var allowedTypes = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                const long maxFileSize = 5 * 1024 * 1024;

                var uploadsDir = Path.Combine(_env.WebRootPath, "uploads");
                if (!Directory.Exists(uploadsDir))
                    Directory.CreateDirectory(uploadsDir);

                foreach (var file in files)
                {
                    if (file == null || file.Length == 0)
                        continue;

                    // 文件大小校验
                    if (file.Length > maxFileSize)
                        return this.ValidationFailResult($"文件 {file.FileName} 大小不能超过5MB");

                    // 文件类型校验
                    var ext = Path.GetExtension(file.FileName).ToLower();
                    if (!allowedTypes.Contains(ext))
                        return this.ValidationFailResult($"文件 {file.FileName} 类型不支持");

                    // 生成唯一文件名并保存
                    var fileName = Guid.NewGuid() + ext;
                    var filePath = Path.Combine(uploadsDir, fileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    urls.Add($"/uploads/{fileName}");
                }

                _logger.LogInformation("批量上传成功: {Count} 个文件", urls.Count);
                
                return this.SuccessResult(new { urls }, $"批量上传成功，共 {urls.Count} 个文件");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量文件上传失败");
                return this.ServerErrorResult("批量文件上传失败");
            }
        }
    }
}
